<template>
  <div id="add-swiper-main">
    <!-- 面包屑 -->
    <div class="breadcrumb-main">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/recommend' }"
          >首页推荐</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/home/recommend/swiper' }"
          >轮播图</el-breadcrumb-item
        >
        <el-breadcrumb-item>{{ addOrEditText }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-button
      type="success"
      plain
      style="margin-top: 20px"
      @click="backPreviousPage"
      >返 回</el-button
    >

    <!-- 表单 -->
    <div id="add-or-edit-form">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
        class="demo-ruleForm"
        size="medium"
      >
        <el-form-item label="名称" prop="swiperName">
          <el-input
            v-model="ruleForm.swiperName"
            autocomplete="off"
            placeholder="请输入轮播图名称"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
            v-model="ruleForm.description"
          ></el-input>
        </el-form-item>
        <div class="type-code">
          <el-form-item label="类型" prop="swiperType">
            <el-select
              v-model="ruleForm.swiperType"
              placeholder="请选择轮播图类型"
              @change="getCode"
              :disabled="canUse"
            >
              <el-option
                v-for="item in options"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeName"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="编码" prop="swiperCode">
            <el-select
              v-model="ruleForm.swiperCode"
              placeholder="请选择编码"
              :disabled="canUse"
            >
              <el-option
                v-for="(item, index) in codeOption"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item
          label="是否显示在APP"
          prop="isShowApp"
          class="is-show-app-form-item"
          label-width="140px"
        >
          <el-switch v-model="ruleForm.isShowApp" active-color="#13ce66">
          </el-switch>
        </el-form-item>
        <el-form-item label="上传图片" prop="uploadImage" label-width="110px">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :multiple="false"
            :http-request="uploadImageFunc"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
              title="点击更换图片"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item class="submit-btn-from-item">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { client } from "../../request/alioss.js";
import { addOrEditSwiper, getCode } from "@/request/home.js";
export default {
  data() {
    var checkCode = (rule, value, callback) => {
      if (this.addOrEditText === "添加") {
        if (this.ruleForm.swiperType === "") {
          callback(new Error("请先选择类型"));
        } else {
          if (!value) {
            callback(new Error("请选择编码"));
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    };
    var checkSwiperType = (rule, value, callback) => {
      if (this.addOrEditText === "添加") {
        if (!value) {
          callback(new Error("请选择类型"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      canUse: true, // 下拉选择器是否可用（编辑不可用，添加可用）
      addOrEditText: "添加轮播", // 添加轮播还是编辑轮播
      ruleForm: {
        swiperName: "",
        description: "",
        swiperType: "",
        isShowApp: true,
        swiperCode: "",
      },
      imageUrl: "",
      options: [
        {
          typeId: "1",
          typeName: "商品",
        },
        {
          typeId: "2",
          typeName: "酒店",
        },
        {
          typeId: "3",
          typeName: "文章",
        },
        {
          typeId: "4",
          typeName: "资讯",
        },
      ],
      // codeOption: ["goods0001", "goods0001", "goods0001", "goods0001"],
      codeOption: [],
      rules: {
        swiperName: [
          { required: true, message: "请输入轮播图名称", trigger: "blur" },
          // { validator: validatePass, trigger: "blur" },
        ],
        swiperType: [
          { validator: checkSwiperType, trigger: ["blur", "change"] },
        ],
        swiperCode: [{ validator: checkCode, trigger: ["blur", "change"] }],
      },
    };
  },
  mounted() {
    this.addOrEditText = this.$route.query.name + "轮播";

    if (this.$route.query.name === "编辑") {
      const row = this.$route.query.row;
      console.log(row);
      this.ruleForm.swiperName = row.name;
      this.ruleForm.description = row.description;
      this.ruleForm.swiperType = row.type;
      this.ruleForm.swiperCode = row.swiperCode;
      this.ruleForm.isShowApp = row.isShowApp;
      this.imageUrl = row.url;
      this.canUse = true;
    } else {
      this.canUse = false;
    }
  },
  methods: {
    // 图片上传成功返回URL
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },

    // 上传图片
    uploadImageFunc(file) {

      

      // 定义唯一文件名
      var fileName =
        (this.ruleForm.swiperName === "" ? "" : this.ruleForm.swiperName) +
        `${Date.parse(new Date())}` +
        ".jpg";
      // console.log(fileName);
      // 指定上传的完整路径，包含目标文件夹
      var fullPath = "jy_back/swipers/home/" + fileName;
      // console.log(fullPath);
      client()
        .multipartUpload(fullPath, file.file)
        .then((res) => {
          // console.log(res);
          this.$message.success("上传成功！");
          this.imageUrl =
            "https://fzg-jy.oss-cn-hangzhou.aliyuncs.com/" + res.name;
          // console.log(this.imageUrl);
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("上传失败，请重试...");
        });
    },

    // 图片上传失败提示
    handleAvatarError() {
      this.$message.error("上传失败，请重试...");
    },

    // 提交
    submitForm(formName) {
      // console.log("提交");
      // console.log(this.ruleForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          // console.log(this.ruleForm);
          if (this.imageUrl === "") {
            this.$message.info("请先上传图片");
          } else {
            // console.log("表单数据");
            const data = {
              addOrEditText: this.addOrEditText,
              ...this.ruleForm,
              swiperImgUrl: this.imageUrl,
            };
            // console.log(data);
            // 提交到后端更新或存储
            addOrEditSwiper(data)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success(res.data.message);
                } else {
                  this.$message.error(this.addOrEditText + "失败，请重试！");
                }
              })
              .catch((err) => {
                this.$message.error(this.addOrEditText + "失败，请重试！");
                console.log(err);
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.imageUrl = "";
    },
    // 返回上一页
    backPreviousPage() {
      this.$router.back();
    },
    // 当类型改变时，code从后端获取
    getCode() {
      this.codeOption = [];
      this.ruleForm.swiperCode = "";
      const param = {
        typeName: this.ruleForm.swiperType,
      };
      // console.log(this.codeOption )
      getCode(param)
        .then((res) => {
          // console.log(res);
          this.codeOption = res.data;
        })
        .catch((err) => {
          console.log(err);
          this.codeOption = [];
        });
    },
  },
};
</script>

<style scoped>
#add-or-edit-form {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
  /* background-color: #fff; */
}
.demo-ruleForm {
  padding: 30px;
  background-color: #fff;
  width: 800px;
  box-shadow: 5px 5px 10px 2px rgba(0, 0, 0, 0.3);
}

.is-show-app-form-item {
  margin-top: 30px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.submit-btn-from-item {
  margin-top: 30px;
}
.type-code {
  display: flex;
  justify-content: space-between;
}
</style>
